package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.cdcz;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.kafka.JFKafkaProducer;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.models.KafkaMessage;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.shared_device.base.enums.ELogState;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.base.models.OrderLogContent;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZOrder;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZOrderChargeLog;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZOrderDeviceLog;
import com.gzhryc.shared_device.cdcz.code.dao.enums.CDCZOrderEnum;
import com.gzhryc.shared_device.cdcz.code.dao.models.CDCZOrderDeviceLogContent;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderChargeLogService;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderDeviceLogService;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderService;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkService;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.oem.code.HttpNetworkServiceUtils;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.order.RedisCacheManager;
import com.gzhryc.shared_device.oem.code.order.dao.models.CDCZOrderUser;
import com.gzhryc.shared_device.oem.code.order.event.OrderFinishEvent;
import com.gzhryc.shared_device.oem.code.order.services.CDCZOrderUserService;
import com.gzhryc.shared_device.oem.code.order.services.dto.CDCZOrderUserSearch;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceClerk;
import com.gzhryc.shared_device.oem.code.place.services.PlaceClerkService;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrder;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUser;
import com.gzhryc.shared_device.oem.code.profit.dao.enums.BusinessOrderEnum;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderService;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderUserService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.cdcz.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CDCZOrderController {

    static Logger log = Logger.getLogger(CDCZOrderController.class);

    @Route(value = "/agent/api/v1/cdcz/order/list.data")
    public CDCZOrderListResponse list(HttpServletRequest request){
        CDCZOrderListResponse apiResp = new CDCZOrderListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        CDCZOrderListRequest apiReq = WebUtils.getJsonRequest(request, CDCZOrderListRequest.class);
        if (apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Integer pageNo = apiReq.getBody().getPageNo() == null ? 1 : apiReq.getBody().getPageNo();

                Date currentDate = new Date();
                if(StringTools.isNotBlank(apiReq.getBody().getYear())){
                    try {
                        currentDate = DateUtils.parseDate(apiReq.getBody().getYear(),"yyyy");
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                }

                if(!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    if (loginUser.getParentId() == null) {
                        apiResp.setMsg("无权限查看");
                        return apiResp;
                    }
                }

                CDCZOrderUserSearch search = new CDCZOrderUserSearch();
                search.setUserId(loginUser.getId());
                search.setPlaceUserId(loginUser.getParentId());
                search.setDeviceSn(apiReq.getBody().getDeviceSn());

                //'全部','使用中','开启失败','已完成','已撤销','开启中'
                if(apiReq.getBody().getDeviceOrderState() != null){
                    if(apiReq.getBody().getDeviceOrderState() == 1){
                        search.setNotPayState(CDCZOrderEnum.PayState.Cancel.index());
                        search.setDeviceOrderState(CDCZOrderEnum.State.Working.index());
                    }else if(apiReq.getBody().getDeviceOrderState() == 2){
                        search.setDeviceOrderState(CDCZOrderEnum.State.Fail.index());
                    }else if(apiReq.getBody().getDeviceOrderState() == 3){
                        search.setNotPayState(CDCZOrderEnum.PayState.Cancel.index());
                        search.setDeviceOrderState(CDCZOrderEnum.State.Finish.index());
                    }else if(apiReq.getBody().getDeviceOrderState() == 4){
                        search.setPayState(CDCZOrderEnum.PayState.Cancel.index());
                    }else if(apiReq.getBody().getDeviceOrderState() == 5){
                        search.setNotPayState(CDCZOrderEnum.PayState.Cancel.index());
                        search.setDeviceOrderState(CDCZOrderEnum.State.Opening.index());
                    }
                }
                search.setTrim(apiReq.getBody().getTrim());
                List<CDCZOrderUser> orderUserList = CDCZOrderUserService.self(currentDate).findJoinBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
                if(orderUserList != null && orderUserList.size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    for (CDCZOrderUser orderUser : orderUserList){
                        CDCZOrder deviceOrder = orderUser.getDeviceOrder();
                        CDCZOrderListResponse.Item item = new CDCZOrderListResponse.Item();
                        item.setTradeNo(deviceOrder.getTradeNo());
                        item.setDeviceSn(deviceOrder.getChargeSocketSn());
                        item.setMemberId(deviceOrder.getMemberId());
                        item.setMemberName(deviceOrder.getMemberName());
                        item.setLeasePlaceId(deviceOrder.getPlaceId());
                        item.setLeasePlaceName(deviceOrder.getPlaceName());
                        item.setLeaseSlotNum(deviceOrder.getSlotNum());
                        item.setCostModeName(deviceOrder.getCostModeName());
                        item.setMoneyStr(deviceOrder.getMoneyStr());
                        item.setPayState(deviceOrder.getPayState());
                        item.setPayStateName(deviceOrder.getPayStateName());
                        item.setDeviceOrderState(deviceOrder.getState());
                        item.setDeviceOrderStateName(deviceOrder.getStateName());
                        item.setCreateDate(deviceOrder.getCreateDate());
                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdcz/order/info.data")
    public CDCZOrderInfoResponse info(HttpServletRequest request) {
        CDCZOrderInfoResponse apiResp = new CDCZOrderInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        CDCZOrderInfoRequest apiReq = WebUtils.getJsonRequest(request, CDCZOrderInfoRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Date createDate = new Date();
                if(StringTools.isNotBlank(apiReq.getBody().getCreateDate())){
                    try {
                        createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(),"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd");
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                }
                
                Long userId = loginUser.getId();
                
                if(ERoleType.Clerk.index().equals(loginUser.getRoleType())) {
                	//如果是店员，则检查商户有没有权限控制该订单
                	userId = loginUser.getParentId();
                }
                
                BusinessOrderUser businessOrderUser = BusinessOrderUserService.self(createDate).getByKeys(apiReq.getBody().getTradeNo(),userId);
                if(businessOrderUser == null || businessOrderUser.getPlaceUserId() == null){
                    apiResp.setMsg("无权限查看");
                    return apiResp;
                }

                CDCZOrder deviceOrder = CDCZOrderService.self(businessOrderUser.getCreateDate()).getByTradeNo(apiReq.getBody().getTradeNo());
                if (deviceOrder != null) {
                	//如果是店员，还需要检查是否有网点的权限
                	if(ERoleType.Clerk.index().equals(loginUser.getRoleType())) {
                		PlaceClerk placeClerk = PlaceClerkService.self().getByKeys(deviceOrder.getPlaceId(),loginUser.getId());
                		if(placeClerk == null) {
                			 apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                             return apiResp;
                		}
                	}
                	
                    CDCZOrderInfoResponse.Body body = ClassTools.copy(new CDCZOrderInfoResponse.Body(), deviceOrder);
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    body.setStateName(deviceOrder.getStateName());
                    body.setPayStateName(deviceOrder.getPayStateName());
                    body.setMoneyStr(deviceOrder.getMoneyStr());
                    body.setPayMoneyStr(deviceOrder.getPayMoneyStr());
                    body.setBusinessOrderState(businessOrderUser.getState());
                    body.setBusinessOrderStateName(businessOrderUser.getStateName());
                    apiResp.setBody(body);

                    CDCZOrderDeviceLog deviceLog = CDCZOrderDeviceLogService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                    if (deviceLog != null && StringTools.isNotBlank(deviceLog.getContent())) {
                        CDCZOrderDeviceLogContent logContent = JsonTools.fromJson(deviceLog.getContent(), CDCZOrderDeviceLogContent.class);
                        CDCZOrderInfoResponse.PolygonalLineData polygonalLineData = new CDCZOrderInfoResponse.PolygonalLineData();
                        polygonalLineData.setCategories(new ArrayList<>());
                        polygonalLineData.setSeries(new ArrayList<>());
                        CDCZOrderInfoResponse.SeriesItem seriesItem = new CDCZOrderInfoResponse.SeriesItem();
                        seriesItem.setName("功率");
                        seriesItem.setData(new ArrayList<>());
                        polygonalLineData.getSeries().add(seriesItem);

                        seriesItem = new CDCZOrderInfoResponse.SeriesItem();
                        seriesItem.setName("电流");
                        seriesItem.setData(new ArrayList<>());
                        polygonalLineData.getSeries().add(seriesItem);

                        for (CDCZOrderDeviceLogContent.LogItem logItem : logContent.getItems()) {
                            polygonalLineData.getCategories().add(DateFormatUtils.format(logItem.getDate(), "HH:mm"));

                            seriesItem = polygonalLineData.getSeries().get(0);
                            seriesItem.getData().add(logItem.getInstantPower());

                            seriesItem = polygonalLineData.getSeries().get(1);
                            seriesItem.getData().add(logItem.getInstantCurrent());
                        }

                        apiResp.getBody().setPolygonalLineData(polygonalLineData);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdcz/order/charge_record/list.data")
    public CDCZOrderChargeRecordListResponse operateRecordListData(HttpServletRequest request) {
        CDCZOrderChargeRecordListResponse apiResp = new CDCZOrderChargeRecordListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        CDCZOrderChargeRecordListRequest apiReq = WebUtils.getJsonRequest(request, CDCZOrderChargeRecordListRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Date createDate = new Date();
                if (StringTools.isNotBlank(apiReq.getBody().getCreateDate())) {
                    try {
                        createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");
                    } catch (ParseException e) {
                        log.error(e.getMessage(), e);
                    }
                }
                BusinessOrderUser businessOrderUser = BusinessOrderUserService.self(createDate).getByKeys(apiReq.getBody().getTradeNo(),loginUser.getId());
                if(businessOrderUser == null || businessOrderUser.getPlaceUserId() == null){
                    apiResp.setMsg("无权限查看");
                    return apiResp;
                }

                if (!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    if (loginUser.getParentId() == null || !businessOrderUser.getPlaceUserId().equals(loginUser.getParentId())) {
                        apiResp.setMsg("无权限查看");
                        return apiResp;
                    }
                }

                List<CDCZOrderChargeLog> orderChargeLogList = CDCZOrderChargeLogService.self(createDate).findByTradeNo(apiReq.getBody().getTradeNo());
                if (orderChargeLogList != null && orderChargeLogList.size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    for (CDCZOrderChargeLog orderChargeLog : orderChargeLogList) {
                        if (StringTools.isNotBlank(orderChargeLog.getContent())) {
                            OrderLogContent logContent = JsonTools.fromJson(orderChargeLog.getContent(), OrderLogContent.class);
                            if (logContent != null && logContent.getItems() != null && logContent.getItems().size() > 0) {
                                for (OrderLogContent.LogItem logItem : logContent.getItems()) {
                                    CDCZOrderChargeRecordListResponse.Item item = new CDCZOrderChargeRecordListResponse.Item();
                                    item.setCreateDate(logItem.getCreateDate());
                                    item.setContent(logItem.getContent());
                                    item.setState(logItem.getState());
                                    item.setStateName(ELogState.note(logItem.getState()));
                                    item.setErrorsMsg(logItem.getErrorMsg());
                                    apiResp.getBody().getItems().add(item);
                                }
                            }
                        }
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdcz/order/cancel.do")
    public DefaultAPIResponse cancel(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "撤销订单失败");
        CDCZOrderCancelRequest apiReq = WebUtils.getJsonRequest(request, CDCZOrderCancelRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
            if (StringTools.isBlank(apiReq.getBody().getNote())) {
                apiResp.setMsg("请填写撤销说明");
                return apiResp;
            }
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Date createDate = new Date();
                if(StringTools.isNotBlank(apiReq.getBody().getCreateDate())){
                    try {
                        createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(),"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd");
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                }

                BusinessOrderUser businessOrderUser = BusinessOrderUserService.self(createDate).getByKeys(apiReq.getBody().getTradeNo(), loginUser.getId());
                if (businessOrderUser == null || businessOrderUser.getPlaceUserId() == null) {
                    apiResp.setMsg("无权限查看");
                    return apiResp;
                }

                if (!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    if (loginUser.getParentId() == null || !businessOrderUser.getPlaceUserId().equals(loginUser.getParentId())) {
                        apiResp.setMsg("无权限查看");
                        return apiResp;
                    }
                }

                CDCZOrder deviceOrder = CDCZOrderService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                if (deviceOrder == null) {
                    apiResp.setMsg("未找到设备订单");
                    return apiResp;
                }

                //检查分成
                BusinessOrder businessOrder = BusinessOrderService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                if(businessOrder != null && (BusinessOrderEnum.DivideState.Finish.index().equals(businessOrder.getDivideState())
                        || BusinessOrderEnum.DivideState.CancelExecuting.index().equals(businessOrder.getDivideState()))){
                    apiResp.setMsg("订单已分成，请回滚分成后操作");
                    return apiResp;
                }

                ICDCZNetworkService networkService = HttpNetworkServiceUtils.getCDCZNetworkService(deviceOrder.getIotId());

                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getNickname());
                operateInfo.setOperateNote("[撤销订单]" + apiReq.getBody().getNote());

                Date cancelDate = new Date();
                try {
                    int result = CDCZOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder, PayServiceFactory.self(), networkService, operateInfo);
                    if (result > 0) {
                        //清理缓存，避免定时器重复处理
                        RedisCacheManager.removeWorkingCDCZDeviceOrder(deviceOrder.getTradeNo());
                        if (result == 2) {
                            deviceOrder = CDCZOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo()); //获取新数据信息
                            //同步会员订单
                            MemberBusinessOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder.getTradeNo(),deviceOrder.getMoney()
                                    ,deviceOrder.getPayMoney(),deviceOrder.getWalletMoney());
                            BusinessOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder.getTradeNo(), cancelDate);
                        }
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdcz/order/finish.do")
    public DefaultAPIResponse finish(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "完成订单失败");
        CDCZOrderFinishRequest apiReq = WebUtils.getJsonRequest(request, CDCZOrderFinishRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo()) && apiReq.getBody().getMoney() != null) {
            if (StringTools.isBlank(apiReq.getBody().getNote())) {
                apiResp.setMsg("请填写撤销说明");
                return apiResp;
            }
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Date createDate = new Date();
                if(StringTools.isNotBlank(apiReq.getBody().getCreateDate())){
                    try {
                        createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(),"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd");
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                }

                BusinessOrderUser businessOrderUser = BusinessOrderUserService.self(createDate).getByKeys(apiReq.getBody().getTradeNo(), loginUser.getId());
                if (businessOrderUser == null || businessOrderUser.getPlaceUserId() == null) {
                    apiResp.setMsg("无权限查看");
                    return apiResp;
                }

                if (!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    if (loginUser.getParentId() == null || !businessOrderUser.getPlaceUserId().equals(loginUser.getParentId())) {
                        apiResp.setMsg("无权限查看");
                        return apiResp;
                    }
                }

                CDCZOrder deviceOrder = CDCZOrderService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                if (deviceOrder == null) {
                    apiResp.setMsg("未找到设备订单");
                    return apiResp;
                }
                ICDCZNetworkService networkService = HttpNetworkServiceUtils.getCDCZNetworkService(deviceOrder.getIotId());

                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator( EOperatorType.Agent.index(), loginUser.getNickname());
                operateInfo.setOperateNote("[完成订单]" + apiReq.getBody().getNote());

                try {
                    int result = CDCZOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder, NumberTools.changeMoney(apiReq.getBody().getMoney()), PayServiceFactory.self()
                            , networkService, operateInfo);
                    if (result > 0) {
                        //清理缓存，避免定时器重复处理
                        RedisCacheManager.removeWorkingCDCZDeviceOrder(deviceOrder.getTradeNo());
                        if (result == 2) {
                            deviceOrder = CDCZOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                            //同步会员订单
                            MemberBusinessOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder.getTradeNo(),deviceOrder.getMoney(), deviceOrder.getPayMoney()
                                    , deviceOrder.getWalletMoney(),operateInfo);

                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderFinishEvent event = new OrderFinishEvent(EBusinessType.CDCZ.index(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate(), operateInfo);
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_OrderFinish, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            }else{
                                log.error("未初始化消息队列，订单{{0}}未触发完成事件",deviceOrder.getTradeNo());
                            }
                        }
                        apiResp.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdcz/order/refund.do")
    public DefaultAPIResponse refund(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "订单退款失败");
        CDCZOrderRefundRequest apiReq = WebUtils.getJsonRequest(request, CDCZOrderRefundRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getTradeNo()) && apiReq.getBody().getMoney() != null) {
            if (StringTools.isBlank(apiReq.getBody().getNote())) {
                apiResp.setMsg("请填写退款说明");
                return apiResp;
            }
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Date createDate = new Date();
                if(StringTools.isNotBlank(apiReq.getBody().getCreateDate())){
                    try {
                        createDate = DateUtils.parseDate(apiReq.getBody().getCreateDate(),"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd");
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                }

                BusinessOrderUser businessOrderUser = BusinessOrderUserService.self(createDate).getByKeys(apiReq.getBody().getTradeNo(), loginUser.getId());
                if (businessOrderUser == null || businessOrderUser.getPlaceUserId() == null) {
                    apiResp.setMsg("无权限查看");
                    return apiResp;
                }

                if (!ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    if (loginUser.getParentId() == null || !businessOrderUser.getPlaceUserId().equals(loginUser.getParentId())) {
                        apiResp.setMsg("无权限查看");
                        return apiResp;
                    }
                }

                CDCZOrder deviceOrder = CDCZOrderService.self(createDate).getByTradeNo(apiReq.getBody().getTradeNo());
                if (deviceOrder == null) {
                    apiResp.setMsg("未找到设备订单");
                    return apiResp;
                }

                //检查分成
                BusinessOrder businessOrder = BusinessOrderService.self(new Date()).getByTradeNo(apiReq.getBody().getTradeNo());
                if(businessOrder != null && (BusinessOrderEnum.DivideState.Finish.index().equals(businessOrder.getDivideState())
                        || BusinessOrderEnum.DivideState.CancelExecuting.index().equals(businessOrder.getDivideState()))){
                    apiResp.setMsg("订单已分成，请回滚分成后操作");
                    return apiResp;
                }

                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator( EOperatorType.Agent.index(), loginUser.getNickname());
                operateInfo.setOperateNote("[退款]" + apiReq.getBody().getNote());

                try {
                    int result = CDCZOrderService.self(deviceOrder.getCreateDate()).refund(deviceOrder, NumberTools.changeMoney(apiReq.getBody().getMoney())
                            ,PayServiceFactory.self(), operateInfo);
                    if (result > 0) {
                        apiResp.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }

}
